package web

import (
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"net/http"
	"testPaper/common"
	"testPaper/model"
	"testPaper/response"
)

// CreatCompany 创建公司用户
func CreatCompany(c *gin.Context) {
	DB := common.GetDB()
	name := c.PostForm("name")
	telephone := c.PostForm("telephone")
	adminPhone := c.PostForm("adminPhone")

	if len(name) == 0 {
		response.Reponse(c, http.StatusOK, 422, nil, "用户名不能为空")
		return
	} else if len(telephone) != 11 {
		response.Reponse(c, http.StatusOK, 422, nil, "手机号格式错误")
		return
	} else if len(adminPhone) != 11 {
		response.Reponse(c, http.StatusOK, 422, nil, "管理员绑定不正确")
		return
	}
	if isAdminPhoneExits(DB, adminPhone) {
		company := model.Company{
			Name:       name,
			Telephone:  telephone,
			AdminPhone: adminPhone,
		}
		DB.Create(&company)
		response.Reponse(c, http.StatusOK, 200, nil, "创建成功")
	} else {
		response.Reponse(c, http.StatusOK, 422, nil, "管理员账号不存在")
		return
	}

}

func isAdminPhoneExits(db *gorm.DB, adminPhone string) bool {
	var admin model.Admin
	db.Where("telephone = ?", adminPhone).First(&admin)
	if admin.ID != 0 {
		return true
	}
	return false
}
